﻿#!/usr/bin/env python3

import socket
import binascii

def main():
    '''socket samples -  '''
    print(main.__doc__)
    print("="*30)

    print('-'*10, 'gethostname')
    print(socket.gethostname())

    print('-'*10, 'gethostbyname')
    hostnames = ['localhost', 'www.baidu.com', 'www.python.org', 'weibo.com']
    for host in hostnames:
        try:
            print("{0}, {1}".format(host, socket.gethostbyname(host)))
        except OSError as err:
            print("{0} {1}".format(host, err))

    print('-'*10, 'gethostbyname_ex')
    for host in hostnames:
        try:
            hostname, aliases, addrs = socket.gethostbyname_ex(host)
            print("hostname:{0}, aliases:{1}, addrs:{2}".format(hostname, aliases, addrs))
        except OSError as err:
            print("{0} {1}".format(host, err))

    print('-'*10, 'gethostbyaddr')
    ips=['127.0.0.1', '151.101.228.223', '123.125.104.26']
    for ip in ips:
        try:
            hostname, aliases, addrs = socket.gethostbyaddr(ip)
            print("hostname:{0}, aliases:{1}, addrs:{2}".format(hostname, aliases, addrs))
        except OSError as err:
            print("{0} {1}".format(ip, err))

    print('-'*10, 'getservbyname')
    servnames=['http', 'https', 'ftp', 'smtp', 'pop3', 'pop3s']
    for sn in servnames:
        print("{0:>6}, port:{1}".format(sn, socket.getservbyname(sn)))

    print('-'*10, 'getprotobyname')
    protocols = dict((getattr(socket, n), n) for n in dir(socket) if n.startswith('IPPROTO_'))
    protonames=['icmp', 'udp', 'tcp']
    for proto in protonames:
        protonum = socket.getprotobyname(proto)
        print("{0:>6}, {1}, {2}".format(proto, protonum, protocols[protonum]))

    print('-'*10, 'aton and ntoa')
    ips = ['127.0.0.1', '192.168.1.1']
    for ip in ips:
        packed = socket.inet_aton(ip)
        print("ipstr:", ip)
        print("packed:", binascii.hexlify(packed))
        print("unpacked:", socket.inet_ntoa(packed))



if __name__=='__main__':
    main()
